import React, { useState, useEffect, useRef } from 'react';
import Particles, { initParticlesEngine } from "@tsparticles/react";
import { loadSlim } from "@tsparticles/slim";
import type { ISourceOptions } from "@tsparticles/engine";
import type { Engine } from "@tsparticles/engine";
import './GiftAnimation.css';

// Type definitions
interface User {
  nickname: string;
  [key: string]: any;
}

interface Gift {
  id: string;
  name: string;
  price: number;
  image: string;
  animation?: string;
  icon?: string;
  [key: string]: any;
}

interface GiftData {
  fromUser: User;
  gift: Gift;
  timestamp?: number;
}

interface GiftAnimationProps {
  giftQueue: GiftData[];
  onAnimationComplete: () => void;
}

const GiftAnimation: React.FC<GiftAnimationProps> = ({ giftQueue, onAnimationComplete }) => {
  const [init, setInit] = useState<boolean>(false);
  const [activeGift, setActiveGift] = useState<GiftData | null>(null);
  const [animationKey, setAnimationKey] = useState<number>(0);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isProcessingRef = useRef<boolean>(false);
  const animationInProgressRef = useRef<boolean>(false);

  // Initialize particles engine
  useEffect(() => {
    initParticlesEngine(async (engine: Engine) => {
      await loadSlim(engine);
    }).then(() => {
      setInit(true);
    });

    // Cleanup on unmount
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);

  // Debug logging for queue changes
  useEffect(() => {
    console.log(`礼物队列状态: 长度=${giftQueue.length}, 显示中=${activeGift?.gift.name || '无'}, 处理中=${isProcessingRef.current}, 动画中=${animationInProgressRef.current}`);
  }, [giftQueue, activeGift]);

  // 处理礼物队列
  useEffect(() => {
    // 如果没有活动礼物且队列中有礼物，开始处理
    if (!activeGift && giftQueue.length > 0 && !isProcessingRef.current && !animationInProgressRef.current) {
      console.log("开始处理礼物队列");
      processNextGift();
    }
  }, [giftQueue, activeGift]);

  // 处理下一个礼物
  const processNextGift = () => {
    // 防止重复处理
    if (isProcessingRef.current || animationInProgressRef.current) {
      console.log("已有礼物正在处理中，跳过");
      return;
    }

    // 如果队列为空，无需处理
    if (giftQueue.length === 0) {
      console.log("礼物队列为空");
      return;
    }

    // 标记为正在处理
    isProcessingRef.current = true;
    animationInProgressRef.current = true;
    
    // 获取队列中第一个礼物
    const nextGift = giftQueue[0];
    console.log(`开始显示礼物: ${nextGift.gift.name}`);
    
    // 更新动画key以强制重新渲染
    setAnimationKey(prev => prev + 1);
    
    // 设置当前活动礼物
    setActiveGift(nextGift);
    
    // 设置定时器结束动画
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    
    timeoutRef.current = setTimeout(() => {
      console.log(`礼物 ${nextGift.gift.name} 动画完成，准备清理`);
      
      // 清除活动礼物
      setActiveGift(null);
      
      // 重置处理标志
      isProcessingRef.current = false;
      
      // 等待DOM更新后再通知父组件
      setTimeout(() => {
        console.log("通知父组件移除礼物");
        animationInProgressRef.current = false;
        onAnimationComplete();
        
        // 如果队列中还有礼物，继续处理下一个
        if (giftQueue.length > 1) {
          console.log("队列中还有礼物，继续处理");
          setTimeout(processNextGift, 100);
        }
      }, 100);
    }, 2000);
  };

  // 确保动画正常进行的备用检查
  useEffect(() => {
    const timer = setTimeout(() => {
      if (giftQueue.length > 0 && !activeGift && !isProcessingRef.current && !animationInProgressRef.current) {
        console.log("备用检查触发，重新处理礼物队列");
        processNextGift();
      }
    }, 1000);
    
    return () => clearTimeout(timer);
  }, [giftQueue, activeGift]);

  // Don't render if not initialized or no active gift
  if (!init || !activeGift) {
    return null;
  }

  const { fromUser, gift } = activeGift;
  const giftImageSrc = gift.icon || gift.image;

  // Get particles configuration based on gift type
  const getParticlesOptions = (): ISourceOptions => {
    return {
      fullScreen: { enable: false },
      particles: {
        number: {
          value: 80,
          density: { enable: true, value_area: 800 }
        },
        color: { value: ["#fdcf58", "#757676", "#f27d0c", "#800909", "#f07f13"] },
        shape: { type: "circle" },
        opacity: {
          value: { min: 0.1, max: 0.5 },
          animation: { enable: true, speed: 1, sync: false }
        },
        size: {
          value: { min: 1, max: 5 },
          animation: { enable: true, speed: 5, sync: false }
        },
        move: {
          enable: true,
          speed: 6,
          direction: "top",
          straight: true,
          outModes: "destroy"
        }
      },
      interactivity: {
        detectsOn: "canvas",
        events: { resize: { delay: 0, enable: true } }
      },
      detectRetina: true,
      background: { color: "transparent" },
      emitters: {
        direction: "top",
        position: { x: 50, y: 120 },
        rate: { quantity: 5, delay: 0.15 },
        size: { width: 10, height: 10 }
      }
    } as ISourceOptions;
  };

  return (
    <div className="gift-animation-container" key={`gift-container-${animationKey}`}>
      {gift.id === 'rocket' && (
        <Particles id={`tsparticles-${animationKey}`} options={getParticlesOptions()} />
      )}
      <div className="gift-banner">
        <span className="gift-user">{fromUser.nickname || '匿名用户'}</span>
        <span>&nbsp;送出了&nbsp;</span>
        <span className="gift-name">{gift.name}</span>
      </div>
      <img 
        src={giftImageSrc || '/assets/gifts/default.svg'} 
        alt={gift.name} 
        className={`gift-image ${gift.id}`} 
        onError={(e: React.SyntheticEvent<HTMLImageElement, Event>) => {
          const target = e.target as HTMLImageElement;
          console.log("礼物图片加载失败，使用备用图片");
          target.onerror = null;
          target.src = '/assets/gifts/default.svg';
        }}
      />
    </div>
  );
};

export default GiftAnimation;